#region Using Statements
using DirectZZT.Components;
using DirectZZT.Core;
using DirectZZT.Gameplay;
using DirectZZT.Input;
using DirectZZT.Shared.Core;
using DirectZZT.Shared.Gameplay;
using DirectZZT.Shared.Input;
using DirectZZT.Shared.World;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion

namespace DirectZZT
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class DirectZZTGame : Game, IGameController
    {
        #region Fields

        private GraphicsDeviceManager _graphics;

        private IInputManager _inputManager;
        private WorldManager _worldManager;

        #endregion

        #region Properties

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the DirectZZTGame class.
        /// </summary>
        public DirectZZTGame()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            _inputManager = new KeyboardInputManager();
            _worldManager = new WorldManager();

            RegisterCommands();

            // register services
            this.Services.AddService(typeof(IInputManager), _inputManager);
            this.Services.AddService(typeof(IGameController), this);
        }

        #endregion

        #region Methods

        private void RegisterCommands()
        {
            // definition - system commands
            _inputManager.RegisterCommand("Up", new InputCommand("Up", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Down", new InputCommand("Down", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Left", new InputCommand("Left", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Right", new InputCommand("Right", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Fullscreen", new InputCommand("Fullscreen", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Screenshot", new InputCommand("Screenshot", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("ESC", new InputCommand("ESC", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Menu.Back", new InputCommand("Menu.Back", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Windows.ManageWorlds", new InputCommand("Windows.ManageWorlds", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Windows.ScriptDebugger", new InputCommand("Windows.ScriptDebugger", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Windows.Log", new InputCommand("Windows.Log", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));
            _inputManager.RegisterCommand("Modifiers.Alt", new InputCommand("Modifiers.Alt", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.Hidden | InputCommandFlags.System | InputCommandFlags.Locked));

            // definition - player commands
            _inputManager.RegisterCommand("Shoot", new InputCommand("Shoot", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.None));
            _inputManager.RegisterCommand("ShootLast", new InputCommand("ShootLast", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.None));
            _inputManager.RegisterCommand("Torch", new InputCommand("Torch", InputManagerDevices.Keyboard | InputManagerDevices.Gamepad, InputCommandFlags.None));

            // bind - system commands
            _inputManager.Bind("Up", ConfigurationManager.Get("Input").GetInt32("Bind.Up", (int)Keys.Up));
            _inputManager.Bind("Down", ConfigurationManager.Get("Input").GetInt32("Bind.Down", (int)Keys.Down));
            _inputManager.Bind("Left", ConfigurationManager.Get("Input").GetInt32("Bind.Left", (int)Keys.Left));
            _inputManager.Bind("Right", ConfigurationManager.Get("Input").GetInt32("Bind.Right", (int)Keys.Right));
            _inputManager.Bind("Fullscreen", ConfigurationManager.Get("Input").GetInt32("Bind.Fullscreen", (int)Keys.F9));
            _inputManager.Bind("Screenshot", ConfigurationManager.Get("Input").GetInt32("Bind.Screenshot", (int)Keys.F12));
            _inputManager.Bind("ESC", ConfigurationManager.Get("Input").GetInt32("Bind.ESC", (int)Keys.Escape));
            _inputManager.Bind("Menu.Back", ConfigurationManager.Get("Input").GetInt32("Bind.ESC", (int)Keys.Escape));
            _inputManager.Bind("Windows.ManageWorlds", ConfigurationManager.Get("Input").GetInt32("Bind.Windows.ManageWorlds", (int)Keys.F10));
            _inputManager.Bind("Windows.ScriptDebugger", ConfigurationManager.Get("Input").GetInt32("Bind.Windows.ScriptDebugger", (int)Keys.F11));
            _inputManager.Bind("Windows.Log", ConfigurationManager.Get("Input").GetInt32("Bind.Windows.Log", (int)Keys.F12));
            _inputManager.Bind("Modifiers.Alt", ConfigurationManager.Get("Input").GetInt32("Bind.Modifiers.Alt", (int)Keys.LeftAlt));

            // bind - player commands
            _inputManager.Bind("Shoot", ConfigurationManager.Get("Input").GetInt32("Bind.Shoot", (int)Keys.LeftShift));
            _inputManager.Bind("ShootLast", ConfigurationManager.Get("Input").GetInt32("Bind.ShootLast", (int)Keys.Space));
            _inputManager.Bind("Torch", ConfigurationManager.Get("Input").GetInt32("Bind.Torch", (int)Keys.T));
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: use this.Content to load your game content here
            this.Components.Add(new ScreenManagerComponent(this));

            if (ConfigurationManager.Get("Client").GetBoolean("G.ShowFPS", false))
            {
                this.Components.Add(new FPSComponent(this));
            }

            _worldManager.Scan("");

            // TODO: Add your initialization logic here
            base.Initialize();

            // load graphics device settings
            _graphics.PreferredBackBufferWidth = ConfigurationManager.Get("Client").GetInt32("G.ViewportWidth", 800);
            _graphics.PreferredBackBufferHeight = ConfigurationManager.Get("Client").GetInt32("G.ViewportHeight", 480);
            _graphics.IsFullScreen = ConfigurationManager.Get("Client").GetBoolean("G.ViewportFullscreen", false);
            _graphics.ApplyChanges();

            // check for hardware - detect ANY mobile graphics
            if (!ConfigurationManager.Get("Client").GetBoolean("G.DisableMobileCardCheck", false) && _graphics.GraphicsDevice.Adapter.Description.Contains("Mobil"))
            {
                // dammit!
                // superbadmotherfucker-hack: use fixed time step = false to avoid high cpu loads!

                Logging.GetLogging().LogFormat(LoggingMessageType.Info, "Game", "", "Detected Mobile ({0} [{1}]) graphics. Disabling FixedTimeStep to avoid high CPU loads.", _graphics.GraphicsDevice.Adapter.DeviceName, _graphics.GraphicsDevice.Adapter.VendorId);

                // weird: with this set to "true" the CPU-load actually goes 100% (one core) on ALL mobile cards I've tested! with "false" --> not!
                // also its vice-versa on "regular" machines like my quad core...
                this.IsFixedTimeStep = false;
            }
            else
            {
                this.IsFixedTimeStep = ConfigurationManager.Get("Client").GetBoolean("G.RunCapped", true);
            }
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            _inputManager.Update();

            base.Update(gameTime);

            if (_inputManager.GetActionInvokedToggle("Screenshot"))
            {

            }
            if (_inputManager.GetActionInvokedToggle("Fullscreen"))
            {
                _graphics.ToggleFullScreen();
            }
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            base.Draw(gameTime);
        }

        #endregion

        #region IGameController Members

        /// <summary>
        /// Gets/sets the currently used feature set.
        /// The feature set is determined by the currently loaded world.
        /// </summary>
        public FeatureSet CurrentFeatureSet { get; set; }
        /// <summary>
        /// Returns whether or not the game is paused, that is, it reacts to the player's controls.
        /// </summary>
        public bool IsGamePaused { get; private set; }

        void IGameController.DisplayMessage(string message)
        {

        }

        void IGameController.EndGame(Player sender)
        {

        }

        void IGameController.PauseGame()
        {
            this.IsGamePaused = true;
        }

        void IGameController.ContinueGame()
        {
            this.IsGamePaused = false;
        }

        #endregion
    }
}
